<template>
  <div class="page-calendar">
    <div class="calendar-head">
      <div class="calendar-titbox">
        <el-row style="width:100%">
          <el-col :span="12" style="padding-left: 20px">
            <h1 style="float: left">{{rangeText}}</h1>
            <div style="float: left;margin-left: 50px;line-height: 36px">
              <el-button size="mini" type="primary" plain @click="setView('day')" :type="calendarView == 'day' ? 'primary' : 'default'">{{$L('日')}}</el-button>
              <el-button size="mini" type="primary" plain @click="setView('week')" :type="calendarView == 'week' ? 'primary' : 'default'">{{$L('周')}}</el-button>
              <el-button size="mini" type="primary" plain @click="setView('month')" :type="calendarView == 'month' ? 'primary' : 'default'">{{$L('月')}}</el-button>

            </div>
          </el-col>
          <el-col :span="12" style="text-align: right;padding-right: 20px;line-height: 36px">
            <el-button size="mini" type="primary" plain @click="preMonth" icon="el-icon-caret-left"></el-button>
            <el-button size="mini" type="primary" plain @click="afterMonth" icon="el-icon-caret-right"></el-button>
            <el-button size="mini" type="primary" plain @click="curMonth">{{$L('今天')}}</el-button>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="calendar-box">
      <Calendar
        ref="cal"
        :view="calendarView"
        :week="calendarWeek"
        :month="calendarMonth"
        :theme="calendarTheme"
        :template="getTemplate"
        :schedules="list"
        :taskView="true"
        :useCreationPopup="true"
        @beforeCreateSchedule="onBeforeCreateSchedule"
        @beforeClickSchedule="onBeforeClickSchedule"
        @beforeUpdateSchedule="onBeforeUpdateSchedule"
        disable-click/>
    </div>
    <div class="calendar-menu" :style="calendarMenuStyles">
      <TaskMenu  ref="calendarTaskMenu" :task="calendarTask" updateBefore/>
    </div>
    <TaskAdd v-if="taskAddRef.ready" ref="taskAddRef" :taskId="task_id" :start_at="start_at" :end_at="end_at"></TaskAdd>



  </div>
</template>

<script>

import {$A} from './functions/common.js'
// import Vue from "vue";

import 'tui-date-picker/dist/tui-date-picker.css';
import 'tui-time-picker/dist/tui-time-picker.css';
import 'tui-calendar-hi/dist/tui-calendar-hi.css'

import ViewUI from 'view-design-hi';

import Calendar from "./components/Calendar";
import moment from "moment";
import TaskMenu from "./components/TaskMenu";
import TaskAdd from "./calendarItem/TaskAdd";
// import axios from "axios";

// import {
  // Row,
  // Col,
  // Button,
  // Divider,
  // Avatar,
  // Tooltip,
  // Popover,
  // Dropdown,
  // DropdownMenu,
  // DropdownItem,
  // Dialog,
  // MessageBox
// } from 'element-ui';

//
// Vue.component('ElRow', Row);
// Vue.component('ElCol', Col);
// Vue.component('ElButton', Button);
// Vue.component('ElDivider', Divider);
// Vue.component('EAvatar', Avatar);
// Vue.component('ETooltip', Tooltip);
// Vue.component('EPopover', Popover);
// Vue.component('ElDropdown', Dropdown);
// Vue.component('ElDropdownMenu', DropdownMenu);
// Vue.component('ElDropdownItem', DropdownItem);
// Vue.component('ElDialog', Dialog);
// Vue.component('MessageBox', MessageBox );

Vue.use(ViewUI, {
  modal: {
    checkEscClose: true
  }
});

export default {
  components: {TaskMenu, Calendar,TaskAdd},
  provide() {
    const provider = {};
    const self = this;
    Object.defineProperty(provider, 'root', {
      enumerable: true,
      get: () => self
    });
    return provider;
  },
  data() {
    return {
      start_at:"",
      end_at:"",
      taskAddRef:{
        ready:false,
      },
      taskMenu:{
        ready:false,
      },
      websocket:null,

      task_id:0,
      taskDetail:{},
      cacheTasks:[],
      taskCompleteTemps:[],
      ready:false,
      lists: [],
      nowTime:$A.Time(),

      rangeText: 'Calendar',
      rangeTime: [],

      calendarView: 'month',
      calendarWeek: {},
      calendarMonth: {},
      calendarTheme: {},
      calendarTemplate: {},
      calendarTask: {},
      calendarMenuStyles: {
        top: 0,
        left: 0
      },
      loadTimeout: null,
    }
  },

  activated() {
    this.$refs.cal.resetRender();
    this.setRenderRange();
  },
  mounted() {
    this.setRenderRange();
    this.websocket = this.ws()
  },

  deactivated() {
    this.$store.dispatch("forgetTaskCompleteTemp", true);
  },

  computed: {
    list() {
      this.taskCompleteTemps = this.cacheTasks
      const filterTask = (task, chackCompleted = true) => {
        if (task.archived_at) {
          return false;
        }
        if (task.complete_at && chackCompleted === true) {
          return false;
        }
        if (!task.end_at) {
          return false;
        }
        return task.owner;
      }
      if(!this.cacheTasks){
        return
      }
      let array = this.cacheTasks.filter(task => filterTask(task));
      if (this.taskCompleteTemps.length > 0) {
        let tmps = this.cacheTasks.filter(task => this.taskCompleteTemps.includes(task.id) && filterTask(task, false));
        if (tmps.length > 0) {
          array = $A.cloneJSON(array)
          array.push(...tmps);
        }
      }
      return $A.transforTasks(array).map(data => {
        const isAllday = $A.rightExists(data.start_at, "00:00:00") && $A.rightExists(data.end_at, "23:59:59")
        const task = {
          id: data.id,
          calendarId: String(data.project_id),
          title: data.name,
          body: data.desc,
          isAllDay: isAllday,
          category: isAllday ? 'allday' : 'time',
          start: $A.Date(data.start_at).toISOString(),
          end: $A.Date(data.end_at).toISOString(),
          color: "#515a6e",
          bgColor: data.color || '#E3EAFD',
          borderColor: data.p_color,
          priority: '',
          preventClick: true,
          preventCheckHide: true,
          isChecked: !!data.complete_at,
          //
          complete_at: data.complete_at,
          start_at: data.start_at,
          end_at: data.end_at,
          _time: data._time,
        };
        if (data.p_name) {
          let priorityStyle = `background-color:${data.p_color}`;
          task.priority = `<span class="priority" style="${priorityStyle}">${data.p_name}</span>`;
        }
        if (data.sub_my && data.sub_my.length > 0) {
          task.title = `[+${data.sub_my.length}] ${task.title}`
        }
        if (data.sub_top === true) {
          task.title = `[${this.$L('子任务')}] ${task.title}`
        }
        if (data.flow_item_name) {
          task.title = `[${data.flow_item_name}] ${task.title}`
        }
        if (data.complete_at) {
          task.color = "#c3c2c2"
          task.bgColor = "#f3f3f3"
          task.borderColor = "#e3e3e3"
        } else if (data.overdue || $A.Date(data.end_at, true) < this.nowTime) {
          task.title = `[${this.$L('超期')}] ${task.title}`
          task.color = "#f56c6c"
          task.bgColor = data.color || "#fef0f0"
          task.priority+= `<span class="overdue">${this.$L('超期未完成')}</span>`;
        }
        if (!task.borderColor) {
          task.borderColor = task.bgColor;
        }
        return task;
      });
    },
    getTemplate(){
      this.calendarTemplate = {
        popupDetailBody: (schedule)=> {
          return `
                <div>
                    <p>${schedule.body}</p>
                </div>`;
        },
        popupEdit: function() {
          return 'edit';
        },
        popupDelete: function() {
          return 'delete';
        }
      }
      return this.calendarTemplate
    },
  },

  watch: {

    // wsOpenNum(num) {
    //   if (num <= 1) return
    //   this.wsOpenTimeout && clearTimeout(this.wsOpenTimeout)
    //   this.wsOpenTimeout = setTimeout(() => {
    //     if (this.$route.name == 'manage-calendar') {
    //       this.setRenderRange();
    //     }
    //   }, 5000)
    // }
  },

  methods: {
    /**
     * websocket
     * @param text
     * @returns {*}
     */
    ws(){
      var socket = new WebSocket('wss://unicoder.zippro.cn/youyaboot-admin/ws/openapi/calendar/80022-b902c43d17594ba4a503c4592cdf645f');
      socket.onopen = (event)=> {
        console.log('Connection established');
      }
      socket.onmessage = (event)=> {
        console.log('Client received a message',event);
        let data = JSON.parse(event.data)
        let fun = data.fun
        let param = data.param
        if(fun === 'closeDialog'){
          console.log("关闭")
          this.closeDialog(param)
        }
      }
      socket.onclose = (event)=> {
        console.log('Client lost connection');
      }
      socket.onerror = (event)=> {
        console.log('Client error',event);
      }
      return socket
    },

    $L(text){
      return text
    },
    getTask(time) {
      const timeStart = $A.Date($A.formatDate(time[0] + " 00:00:00")),
        timeEnd = $A.Date($A.formatDate(time[1] + " 23:59:59"));
      let startTime = timeStart.toLocaleString('chinese',{hour12:false})
      let endTime = timeEnd.toLocaleString('chinese',{hour12:false})
      startTime = startTime.replace(/\//g, '-');
      endTime = endTime.replace(/\//g, '-');

      axios({
        method: 'post',
        url: "https://unicoder.zippro.cn/youyaboot-admin/magical_lowcode/openapi/c41d1a2156864b1bbb4abdd6c050f896/get-work-task",
        data: {
          "start_time": startTime,
          "end_time": endTime,
          "userid":14
        }
      }).then((res) => {
        if (res.data.code !== 0) {
          this.$message({
            message: res.data.desc,
            type: 'error',
            showClose: true
          })
        }else{
          let cacheTasks = res.data.data
          this.cacheTasks = cacheTasks.map(item=>{
            return {
              "id": item.id,
              "parent_id": item.parent_id,
              "project_id": item.project_id,
              "column_id": item.column_id,
              "dialog_id": item.dialog_id,
              "flow_item_id": item.flow_item_id,
              "flow_item_name": item.flow_item_name,
              "name": item.name,
              "color": item.color,
              "desc": item.task_desc,
              "start_at": item.start_at,
              "end_at": item.end_at,
              "archived_at": item.archived_at,
              "archived_userid": item.archived_userid,
              "archived_follow": item.archived_follow,
              "complete_at": item.complete_at,
              "userid": item.userid,
              "visibility": item.visibility,
              "p_level": item.p_level,
              "p_name": item.p_name,
              "p_color": item.p_color,
              "sort": item.sort,
              "loop": item.loop,
                  "owner": 1,
              "loop_at": item.loop_at,
              "created_at": item.created_at,
              "updated_at": item.updated_at,
              "deleted_at": item.deleted_at,
              "deleted_userid": item.deleted_userid,
              // "owner": item.owner,
              "file_num": item.file_num,
              "msg_num": item.msg_num,
              "sub_num": item.sub_num,
              "sub_complete":item.sub_complete,
              "percent": item.percent,
              "today": item.today,
              "overdue": item.overdue,
              "task_user": [
                {
                  "id": 30399,
                  "project_id": 12307,
                  "task_id": 26361,
                  "task_pid": 26361,
                  "userid": 1,
                  "owner": 1,
                  "created_at": "2024-08-16 09:00:02",
                  "updated_at": "2024-08-16 09:00:02"
                }
              ],
              "task_tag": item.task_tag,
              "project_name": item.project_name,
              "column_name": item.column_name,
              "visibility_appointor": item.visibility_appointor,
            }
          })
        }
      })
    },

    preMonth() {
      this.$refs.cal.getInstance().prev();
      this.setRenderRange()
    },

    curMonth() {
      this.$refs.cal.getInstance().today();
      this.setRenderRange()
    },

    afterMonth() {
      this.$refs.cal.getInstance().next();
      this.setRenderRange()
    },

    setView(view) {
      this.calendarView = view;
      this.setRenderRange()
    },

    setRenderRange() {
      this.$nextTick(() => {
        const cal = this.$refs.cal.getInstance();
        let options = cal.getOptions();
        let viewName = cal.getViewName();
        let html = [];
        if (viewName === 'day') {
          html.push(this.currentCalendarDate('YYYY.MM.DD'));
        } else if (viewName === 'month' &&
          (!options.month.visibleWeeksCount || options.month.visibleWeeksCount > 4)) {
          html.push(this.currentCalendarDate('YYYY.MM'));
        } else {
          html.push(moment(cal.getDateRangeStart().getTime()).format('YYYY.MM.DD'));
          html.push(' ~ ');
          html.push(moment(cal.getDateRangeEnd().getTime()).format(' MM.DD'));
        }
        this.rangeText = html.join('');
        this.rangeTime = [moment(cal.getDateRangeStart().getTime()).format('YYYY-MM-DD'), moment(cal.getDateRangeEnd().getTime()).format('YYYY-MM-DD')];
        this.getTask(this.rangeTime)
      })
    },

    currentCalendarDate(format) {
      const cal = this.$refs.cal.getInstance();
      let currentDate = moment([cal.getDate().getFullYear(), cal.getDate().getMonth(), cal.getDate().getDate()]);
      return currentDate.format(format);
    },

    onBeforeCreateSchedule({start, end, isAllDay, guide}) {
      // console.log("点击编辑")
      if (isAllDay || this.calendarView == 'month') {
        start = $A.date2string(start.toDate(), "Y-m-d 00:00:00")
        end = $A.date2string(end.toDate(), "Y-m-d 23:59:59")
      } else {
        start = $A.date2string(start.toDate(), "Y-m-d H:i:s")
        end = $A.date2string(end.toDate(), "Y-m-d H:i:s")
      }
      this.start_at = start
      this.end_at = end
      this.taskAddRef.ready = false
      this.$nextTick(()=>{
        this.taskAddRef.ready = true
      })
    },

    onBeforeClickSchedule(event) {
      const {type, schedule} = event;
      let data = this.cacheTasks.find(({id}) => id === schedule.id);
      if (!data) {
        return;
      }
      switch (type) {
        case "check":
          this.calendarMenuStyles = {
            left: `${this.getElementLeft(event.target)}px`,
            top: `${this.getElementTop(event.target) - 8}px`
          }
          this.calendarTask = data;
          this.$nextTick(this.$refs.calendarTaskMenu.show);
          break;

        case "edit":
          let task_id = data;
          if ($A.isJson(data)) {
            if (data.parent_id > 0) {
              this.task_id = data.parent_id;
            } else {
              this.task_id = data.id;
            }
          }
          this.taskAddRef.ready = false
          this.$nextTick(()=>{
            this.taskAddRef.ready = true
          })
          break;

        case "delete":
          MessageBox.confirm('你确定要删除任务【' + data.name + '】吗？','提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            axios({
              method: 'post',
              url: "https://unicoder.zippro.cn/youyaboot-admin/magical_lowcode/openapi/c41d1a2156864b1bbb4abdd6c050f896/del-work-task",
              data: {
                "delList": [data.id]
              }
            }).then((res) => {
              if (res.data.code !== 0) {
                this.$message({
                  message: res.data.desc,
                  type: 'error',
                  showClose: true
                })
              }else{
                // this.$message.success("删除成功")
                this.setRenderRange()
              }
            })
          })
          break;
      }
    },

    onBeforeUpdateSchedule(res) {
      // console.log("诺肉")
      const {changes, schedule} = res;
      let data = this.cacheTasks.find(({id}) => id === schedule.id);
      if (!data) {
        return;
      }
      // console.log(data)
      if (changes.start || changes.end) {
        const cal = this.$refs.cal.getInstance();
        cal.updateSchedule(schedule.id, schedule.calendarId, changes);
        let start_sjc = new Date(changes.start._date).getTime()
        let end_sjc = new Date(changes.end._date).getTime()
        start_sjc = new Date(start_sjc).toLocaleString('chinese', { hour12: false }).replaceAll('/', '-')
        end_sjc = new Date(end_sjc).toLocaleString('chinese', { hour12: false }).replaceAll('/', '-')
        // console.log(start_sjc)
        let info = {
          id:data.id,
          start_at:start_sjc,
          end_at:end_sjc,
        }
        this.updCaledar(info)
      }
    },
    updCaledar(data){
      axios({
        method: 'post',
        url: "https://unicoder.zippro.cn/youyaboot-admin/magical_lowcode/openapi/c41d1a2156864b1bbb4abdd6c050f896/upd-work-task",
        data: data
      }).then((res) => {
        if (res.data.code !== 0) {
          this.$message({
            message: res.data.desc,
            type: 'error',
            showClose: true
          })
        }else{
          // this.$message.success("删除成功")
          this.setRenderRange()
        }
      })
    },

    getElementLeft(element) {
      let actualLeft = element.offsetLeft;
      let current = element.offsetParent;
      while (current !== null) {
        if (current == this.$el) break;
        actualLeft += (current.offsetLeft + current.clientLeft);
        current = current.offsetParent;
      }
      return actualLeft;
    },

    getElementTop(element) {
      let actualTop = element.offsetTop;
      let current = element.offsetParent;
      while (current !== null) {
        if (current == this.$el) break;
        actualTop += (current.offsetTop + current.clientTop);
        current = current.offsetParent;
      }
      return actualTop;
    },

    //下面是web端调用的方法
    closeDialog(){
      this.taskAddRef.ready = false
      this.setRenderRange()
    }
  }
}
</script>
<style lang="scss">
@import "statics/public/css/iview.css";
@import "statics/sass/pages/_.scss";
</style>
